﻿using System;
using System.Web.Mvc;

namespace FinancePortal.Business.Infraestructure
{
    [AttributeUsage(AttributeTargets.Method)]
    public class TransactionalAttribute : ActionFilterAttribute
    {
        private IUnitOfWork _unitOfWork;

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            _unitOfWork = DependencyResolver.Current.GetService<IUnitOfWork>();
            _unitOfWork.BeginTransaction();
            //base.OnActionExecuting(filterContext);
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (filterContext.Exception != null)// && filterContext.ExceptionHandled)
                _unitOfWork.Rollback();
        }

        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            base.OnResultExecuted(filterContext);

            if (filterContext.Exception != null)// && !filterContext.ExceptionHandled)
                _unitOfWork.Rollback();
            else
                _unitOfWork.Commit();
        }
    }
}
